package com.yikaiye.android.yikaiye.ui.fragment;

import androidx.annotation.NonNull;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yikaiye.android.yikaiye.R;
import com.yikaiye.android.yikaiye.base.BaseFragment;
import com.yikaiye.android.yikaiye.config.Constant;
import com.yikaiye.android.yikaiye.databinding.FragmentAllOrderBinding;
import com.yikaiye.android.yikaiye.ui.adapter.ProductListAdapter;
import com.yikaiye.android.yikaiye.ui.fragment.viewmodel.ProductListViewModel;

public class ProductListFragment extends BaseFragment<FragmentAllOrderBinding, ProductListViewModel> {
    private int page = 1;
    private String typeName;
    private ProductListAdapter adapter;

    @Override
    protected ProductListViewModel bindModel() {
        return getViewModel(this, ProductListViewModel.class);
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected void initData() {
        if (getArguments() != null) {
            typeName = getArguments().getString(Constant.NAME_KEY);
        }
        adapter = new ProductListAdapter(mContext);
        binding.recyclerView.setAdapter(adapter);
        adapter.setEmptyViewEnable(true);
        adapter.setEmptyViewLayout(mContext, R.layout.layout_empty_list);
        viewModel.getProductList(page, typeName);
    }

    @Override
    protected void initClick() {
        viewModel.productData.observe(this, productModels -> {
            if (page == 1) {
                adapter.submitList(productModels);
                binding.smartRefreshLayout.finishRefresh();
            } else {
                adapter.addAll(productModels);
                binding.smartRefreshLayout.finishLoadMore();
            }
        });
        binding.smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                viewModel.getProductList(page, typeName);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                viewModel.getProductList(page, typeName);
            }
        });
    }
}
